AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

--models/dav0r/thruster.mdl
local Ground = 1 + 0 + 2 + 8 + 32

function TraceRepulsor(ent, distance, mask)
	local trace = {}
		trace.start = ent:GetPos() + (ent:GetUp() * 15)
		trace.endpos = trace.start + (ent:GetUp() * distance)
		trace.filter = { ent }
		trace.mask = mask
	return util.TraceLine(trace)
end

function TraceDown(ent, distance, mask)
	local trace = {}
		trace.start = ent:GetPos() + (ent:GetUp() * 15)
		trace.endpos = trace.start - Vector(0,0,distance)
		trace.filter = { ent }
		trace.mask = mask
	return util.TraceLine(trace)
end


function ENT:Initialize()
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )

	local phys = self.Entity:GetPhysicsObject()
	
	if (phys:IsValid()) then
		phys:Wake()
	end
	
    self.Entity:SetVar('LastUpdate',CurTime())
		
end


local function On( pl, ent, mul )
	if (!ent:IsValid()) then return false end
	ent:SetVar('RateMult', mul)
	return true
end

local function Off( pl, ent, mul )
	if (!ent:IsValid()) then return false end
	ent:SetVar('RateMult', nil)
	return true
end

sv_gravity = server_settings.Int('sv_gravity',600)

function ENT:PhysicsUpdate( physobj )
	local dt = CurTime() - self.Entity:GetVar('LastUpdate',0)
	local mul = self.Entity:GetVar('RateMult',nil)
	local maxDist = self.Entity:GetVar('distance',200)
	local downonly = self.Entity:GetVar('downonly',0)
	local mask = self.Entity:GetVar('mask',nil)
	
	if mul then
		maxDist = maxDist + (mul * self.Entity:GetVar('rate') *  .01)
		self.Entity:SetVar('distance',maxDist)
	end
	local trace

	if downonly == 1 then
		trace = TraceDown(self.Entity, maxDist, mask)
	else
		trace = TraceRepulsor(self.Entity, maxDist, mask)
	end

	if trace.Hit then
		local dist = maxDist - (trace.Fraction * maxDist )
		local springforce = (dist * self.Entity:GetVar('strength',0)) * -1 * dt
		local dampingforce = self.Entity:GetVar('damping',0) * physobj:GetVelocity() * dt
		
		local force = (springforce * self.Entity:GetUp()) - dampingforce
		
		if downonly == 1 then
			local downforce = (springforce * Vector(0,0,-1)) - dampingforce
			physobj:ApplyForceCenter(downforce)
		else
			physobj:ApplyForceCenter(force)
		end
		if ( trace.Entity:IsValid() ) then
		
			if ( trace.Entity:GetPhysicsObject():IsValid() ) then
			
				local phys = trace.Entity:GetPhysicsObject()
				phys:ApplyForceCenter( force * -1 )
							
			end
			
		end

	end

	self.Entity:SetVar('LastUpdate',CurTime())
end

// register numpad functions
numpad.Register( "Repulsor_On", On )
numpad.Register( "Repulsor_Off", Off )

